<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\TenantUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * 租户用户登录
     */
    public function login(Request $request)
    {
        $loginType = $request->input('loginType', 'username');

        // 根据登录类型设置不同的验证规则
        if ($loginType === 'phone') {
            $validator = Validator::make($request->all(), [
                'phoneNumber' => 'required|string',
                'code' => 'required|string|min:4',
                'loginType' => 'required|string|in:phone,username',
            ]);
        } else {
            $validator = Validator::make($request->all(), [
                'username' => 'required|string',
                'password' => 'required|string|min:6',
                'loginType' => 'string|in:phone,username',
            ]);
        }

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => null
            ], 422);
        }

        $tenantUser = null;

        if ($loginType === 'phone') {
            // 手机号验证码登录
            $tenantUser = $this->loginByPhone($request->phoneNumber, $request->code);
        } else {
            // 用户名密码登录
            $tenantUser = $this->loginByUsername($request->username, $request->password);
        }

        if (!$tenantUser) {
            return response()->json([
                'code' => 401,
                'message' => $loginType === 'phone' ? '手机号或验证码错误' : '用户名或密码错误',
                'data' => null
            ], 401);
        }

        // 更新最后登录信息
        $tenantUser->update([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip()
        ]);

        // 创建访问令牌
        $token = $tenantUser->createToken('tenant-auth-token')->plainTextToken;

        return response()->json([
            'code' => 0,
            'message' => '登录成功',
            'data' => [
                'accessToken' => $token,
                'user' => [
                    'id' => $tenantUser->id,
                    'username' => $tenantUser->username,
                    'email' => $tenantUser->email,
                    'realName' => $tenantUser->name,
                    'phone' => $tenantUser->phone,
                    'roles' => [$tenantUser->role],
                    'homePath' => '/dashboard'
                ]
            ]
        ]);
    }

    /**
     * 用户名密码登录
     */
    private function loginByUsername($username, $password)
    {
        $tenantUser = TenantUser::where(function ($query) use ($username) {
                                $query->where('username', $username)
                                      ->orWhere('email', $username);
                            })
                            ->where('status', TenantUser::STATUS_ACTIVE)
                            ->whereHas('tenant', function ($query) {
                                $query->where('status', Tenant::STATUS_ACTIVE);
                            })
                            ->first();

        if (!$tenantUser || !Hash::check($password, $tenantUser->password)) {
            return null;
        }

        return $tenantUser;
    }

    /**
     * 手机号验证码登录
     */
    private function loginByPhone($phoneNumber, $code)
    {
        // 验证验证码
        if (!$this->verifySmsCode($phoneNumber, $code)) {
            return null;
        }

        // 查找用户
        $tenantUser = TenantUser::where('phone', $phoneNumber)
                               ->where('status', TenantUser::STATUS_ACTIVE)
                               ->whereHas('tenant', function ($query) {
                                   $query->where('status', Tenant::STATUS_ACTIVE);
                               })
                               ->first();

        return $tenantUser;
    }

    /**
     * 验证短信验证码
     */
    private function verifySmsCode($phoneNumber, $code)
    {
        // 开发环境使用万能验证码
        if (app()->environment('local', 'testing')) {
            return in_array($code, ['123456', '000000', '888888']);
        }

        // 这里应该调用短信服务商API验证
        // 暂时返回true，后续集成真实短信服务
        return true;
    }

    /**
     * 发送短信验证码
     */
    public function sendSmsCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phoneNumber' => 'required|string|regex:/^1[3-9]\d{9}$/',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '手机号格式不正确',
                'data' => null
            ], 422);
        }

        $phoneNumber = $request->phoneNumber;
        
        // 开发环境直接返回成功
        if (app()->environment('local', 'testing')) {
            return response()->json([
                'code' => 0,
                'message' => '验证码发送成功，开发环境请使用：123456',
                'data' => null
            ]);
        }

        // 这里应该调用短信服务商API发送验证码
        // 暂时模拟成功返回
        return response()->json([
            'code' => 0,
            'message' => '验证码发送成功，请注意查收',
            'data' => null
        ]);
    }

    /**
     * 租户用户注册（如果允许自注册）
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'tenant_id' => 'sometimes|integer|exists:tenants,id',
            'username' => 'required|string|max:50',
            'email' => 'required|email|max:100',
            'name' => 'required|string|max:50',
            'phone' => 'nullable|string|max:20',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ], 422);
        }

        // 查找租户
        $tenantQuery = Tenant::where('status', Tenant::STATUS_ACTIVE);
        if ($request->filled('tenant_id')) {
            $tenantQuery->where('id', $request->integer('tenant_id'));
        }
        $tenant = $tenantQuery->first();

        if (!$tenant) {
            return response()->json([
                'code' => 404,
                'message' => '租户不存在或已停用',
                'data' => null
            ], 404);
        }

        // 检查邮箱是否已存在
        $existingUser = TenantUser::where('tenant_id', $tenant->id)
                                 ->where('email', $request->email)
                                 ->first();

        if ($existingUser) {
            return response()->json([
                'code' => 409,
                'message' => '该邮箱已被注册',
                'data' => null
            ], 409);
        }

        // 创建租户用户
        $tenantUser = TenantUser::create([
            'tenant_id' => $tenant->id,
            'username' => $request->username,
            'email' => $request->email,
            'name' => $request->name,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'role' => 'user', // 默认角色
            'status' => TenantUser::STATUS_ACTIVE,
            'created_by' => null // 自注册
        ]);

        return response()->json([
            'code' => 0,
            'message' => '注册成功',
            'data' => [
                'user' => [
                    'id' => $tenantUser->id,
                    'username' => $tenantUser->username,
                    'email' => $tenantUser->email,
                    'name' => $tenantUser->name,
                    'phone' => $tenantUser->phone,
                    'role' => $tenantUser->role
                ]
            ]
        ], 201);
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        $user = $request->user();
        
        if (!$user) {
            return response()->json([
                'code' => 401,
                'message' => '用户未认证',
                'data' => null
            ], 401);
        }

        return response()->json([
            'code' => 0,
            'message' => '获取用户信息成功',
            'data' => [
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'realName' => $user->name,
                'phone' => $user->phone,
                'roles' => [$user->role],
                'status' => $user->status,
                'homePath' => '/dashboard'
            ]
        ]);
    }

    /**
     * 获取权限码
     */
    public function codes(Request $request)
    {
        $user = $request->user();
        
        // 根据用户角色返回权限码，为了让用户能进入主页，返回基础权限
        $codes = [
            'dashboard:view',        // 主页查看
            'profile:view',          // 个人信息查看
            'profile:edit',          // 个人信息编辑
        ];
        
        // 根据用户角色添加更多权限
        if ($user && $user->role === 'admin') {
            $codes = array_merge($codes, [
                'user:view',
                'user:create',
                'user:edit',
                'user:delete',
                'task:view',
                'task:create',
                'task:edit',
                'task:delete',
                'system:manage'
            ]);
        } elseif ($user && $user->role === 'operator') {
            $codes = array_merge($codes, [
                'user:view',
                'task:view',
                'task:create',
                'task:edit'
            ]);
        }
        
        return response()->json([
            'code' => 0,
            'message' => '获取权限码成功',
            'data' => $codes
        ]);
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ], 422);
        }

        $user = $request->user();

        // 验证当前密码
        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json([
                'code' => 401,
                'message' => '当前密码错误',
                'data' => null
            ], 401);
        }

        // 更新密码
        $user->update([
            'password' => Hash::make($request->new_password)
        ]);

        return response()->json([
            'code' => 0,
            'message' => '密码修改成功',
            'data' => null
        ]);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        // 删除当前访问令牌
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'code' => 0,
            'message' => '退出登录成功',
            'data' => null
        ]);
    }

    /**
     * 退出所有设备
     */
    public function logoutAll(Request $request)
    {
        // 删除用户的所有访问令牌
        $request->user()->tokens()->delete();

        return response()->json([
            'code' => 0,
            'message' => '已退出所有设备',
            'data' => null
        ]);
    }

    /**
     * 刷新令牌
     */
    public function refresh(Request $request)
    {
        $user = $request->user();
        
        // 删除当前令牌
        $request->user()->currentAccessToken()->delete();
        
        // 创建新令牌
        $token = $user->createToken('tenant-auth-token')->plainTextToken;

        return response()->json([
            'code' => 0,
            'message' => '令牌刷新成功',
            'data' => [
                'token' => $token
            ]
        ]);
    }
}
